from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QDateTime
from PyQt5.QtGui import QFont, QColor, QLinearGradient, QPainter
from pyecharts.charts import Pie
from pyecharts.components import Table
from pyecharts import options as opts
from dao.classorm import classOrm
from dao.exam import Exam
from dao.classRecord import classRecord
from dao.index import LoginSchema
from utils.json import JSONHandler
from components.messageBox import CustomMessageBox
import pandas as pd
from view.lateSign import ModernStudentForm

curJson = JSONHandler("./config/cache.json")

class DashboardView(QWidget):
    """数据看板视图"""
    def __init__(self):
        super().__init__()
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background: transparent;")
        self.initUI()

    # 组装表格需要的数据
    def get_chart_data(self):
        # 获取教师id
        user_id = curJson.read()['user_id']
        # 获取考试名称
        exam_list = Exam().get_exam(user_id)
        print(exam_list)
        # 获取班级数量
        class_count = LoginSchema().get_class_count(exam_list[-1]['class_name'])
        # 获取缺考人数
        absence_count = len(classRecord().export_absence(exam_list[-1]['exam_name'], exam_list[-1]['class_name']))
        # 获取迟到人数
        late_count = len(classRecord().export_late(exam_list[-1]['exam_name']))
        return [class_count, absence_count, late_count]

    def initUI(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)  # 窗口边距
        main_layout.setSpacing(15)  # 元素间距

        # 上半部分布局
        top_layout = QHBoxLayout()
        top_layout.setContentsMargins(0, 0, 0, 0)
        top_layout.setSpacing(15)

        dataLis = self.get_chart_data()

        # 饼图1容器
        pie1 = self.create_pie_chart("迟到占比", [("签到", dataLis[0]), ("迟到", dataLis[-1])])
        web_view1 = self.create_chart_container(pie1)
        top_layout.addWidget(web_view1)

        # 饼图2容器
        pie2 = self.create_pie_chart("缺考占比", [("签到", dataLis[0]), ("缺勤", dataLis[1])])
        web_view2 = self.create_chart_container(pie2)
        top_layout.addWidget(web_view2)

        main_layout.addLayout(top_layout)

        # 表格容器
        table = self.create_table()
        web_view3 = self.create_chart_container(table, show_button=True)  # 启用按钮显示
        main_layout.addWidget(web_view3)

    def create_chart_container(self, chart, show_button=False):
        """创建统一样式容器"""
        container = QFrame()
        
        # 容器样式设置
        container.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.2);
                border: none;
                border-radius: 8px;
            }
        """)
        
        # 内层布局（控制边距）
        layout = QVBoxLayout(container)
        layout.setContentsMargins(12, 12, 12, 12)  # 内边距
        layout.setSpacing(10)

        # 添加导出按钮（当show_button为True时）
        if show_button:
            btn_layout = QHBoxLayout()
            btn_layout.setContentsMargins(0, 0, 0, 0)
            
            export_btn = QPushButton("导出最近一次缺考名单")
            export_btn.setCursor(Qt.PointingHandCursor)
            export_btn.clicked.connect(self.export_absence) 
            export_btn.setStyleSheet("""
                QPushButton {
                    background: rgba(255, 255, 255, 0.3);
                    border: 1px solid rgba(255, 255, 255, 0.5);
                    border-radius: 4px;
                    color: #333;
                    padding: 6px 12px;
                    font-size: 13px;
                }
                QPushButton:hover {
                    background: rgba(255, 255, 255, 0.4);
                }
                QPushButton:pressed {
                    background: rgba(255, 255, 255, 0.2);
                }
            """)
            
            btn_layout.addStretch()
            btn_layout.addWidget(export_btn)
            layout.addLayout(btn_layout)

        # 图表控件
        web_view = QWebEngineView()
        web_view.setHtml(chart.render_embed())
        web_view.setStyleSheet("""
            QWebEngineView {
                background: transparent;
            }
            QWebEngineView::scroll-bar:vertical {
                width: 0px;  /* 隐藏垂直滚动条 */
            }
            QWebEngineView::scroll-bar:horizontal {
                height: 0px; /* 隐藏水平滚动条 */
            }
        """)
        web_view.page().setBackgroundColor(QColor(0, 0, 0, 0))
        
        layout.addWidget(web_view)
        return container

    def create_pie_chart(self, title, data):
        pie = Pie(init_opts=opts.InitOpts(
            bg_color="rgba(0, 0, 0, 0)",  # 图表区域透明
            width="330px",  # 360px - 14px边距
            height="176px", # 200px - 24px边距
        ))
        pie.set_global_opts(
            title_opts=opts.TitleOpts(
                title=title,
                title_textstyle_opts=opts.TextStyleOpts(color="#333")
            ),
            legend_opts=opts.LegendOpts(
                is_show=False,
                textstyle_opts=opts.TextStyleOpts(color="#333")
            )
        )
        pie.add("", data)
        return pie

    def create_table(self):
        table = Table()
    
        # 设置表格尺寸（调整到1200px宽度使列更宽松）
        table.set_global_opts(
            opts.InitOpts(width="1200px", height="450px")  # 增加宽度和高度
        )
        
        # 新表头
        headers = ["序号", "考试名称", "学号", "姓名", "班级", "教师", "签到时间", "考试时间"]
        # 获取教师id
        user_id = curJson.read()['user_id']
        # 获取考试名称
        exam_list = Exam().get_exam(user_id)
        print("考试数据====>", exam_list)
        res = classRecord().export_data(exam_list[-1]['exam_name'], exam_list[-1]['class_name'])
        
        # 模拟数据
        rows = [[i['id'],i['exam_name'], i['student_number'], i['student_name'],i['exam_class'],i['teacher_name'], i['sign_in_time'], i['exam_start_time']]  for i in res]
        print("表格数据====>", rows)
        # 添加数据时通过opts.TableOpts配置表格样式
        table.add(
            headers, 
            rows
        )
        
        return table
    
    def export_absence(self):
        # 获取教师id
        user_id = curJson.read()['user_id']
        # 获取考试名称
        exam_list = Exam().get_exam(user_id)
        # 点击按钮时才调用导出数据方法
        res = classRecord().export_absence(exam_list[0]['exam_name'], exam_list[0]['class_name'])
        # 构建数据字典
        dic = {
            "序号": [i['id'] for i in res],
            "考试科目": [i['exam_name'] for i in res],
            "学号": [i['student_number'] for i in res],
            "姓名": [i['student_name'] for i in res],
            "班级": [i['exam_class'] for i in res],
            "教师": [i['teacher_name'] for i in res],
            "签到时间": [i['sign_in_time'] for i in res],
            "考试开始时间": [i['exam_start_time'] for i in res]
        }
        df = pd.DataFrame(dic)
        df.to_excel("D://Edge//absence.xlsx", index=False)
        CustomMessageBox().show_success("导出成功")


class ExamView(QWidget):
    """考试发布视图"""
    def __init__(self):
        super().__init__()
        self.exams = []  # 存储考试数据
        self.json = JSONHandler("./config/cache.json")
        self.initUI()
        self.init_example_data()

    def initUI(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)

        # 发布考试表单容器
        form_container = QWidget()
        form_container.setObjectName("formContainer")
        self.create_form(form_container)
        main_layout.addWidget(form_container)

        # 考试列表容器
        list_container = QWidget()
        list_container.setObjectName("listContainer")
        self.create_exam_list(list_container)
        main_layout.addWidget(list_container)

        # 样式设置
        self.setStyleSheet("""
            #formContainer, #listContainer {
                background-color: rgba(255, 255, 255, 0.8);
                border-radius: 15px;
                padding: 20px;
            }
            QLabel {
                color: #444444;
                font-size: 14px;
            }
            QLineEdit, QComboBox, QDateTimeEdit {
                border: 2px solid #e0e0e0;
                border-radius: 8px;
                padding: 8px;
                font-size: 14px;
            }
            QComboBox QAbstractItemView {
                background-color: white;
                border: 1px solid #e0e0e0;
                selection-background-color: #e3f2fd;
                outline: 0px;
            }
            QPushButton {
                background-color: #2196F3;
                color: white;
                border: none;
                border-radius: 8px;
                padding: 5px 8px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #1e88e5;
            }
            QTableWidget {
                border: none;
                background-color: transparent;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 10px;
                font-size: 14px;
            }
            QTableWidget {
                border-radius: 12px;
                padding: 5px;
                background-color: rgba(255, 255, 255, 0.9);
                alternate-background-color: #f8f9fa;
                font-size: 14px;
                color: #555555;
                selection-background-color: rgba(33, 150, 243, 0.2);
                selection-color: #2196F3;
            }
            QHeaderView {
                background-color: qlineargradient(
                    x1:0, y1:0, x2:0, y2:1,
                    stop:0 #f8f9fa, stop:1 #e9ecef
                );
                border-radius: 8px;
                padding-left: 15px;
            }
            QHeaderView::section {
                background-color: transparent;
                color: #495057;
                padding: 12px;
                border: none;
                font-weight: 500;
                font-size: 14px;
            }
            QTableWidget::item {
                border-bottom: 1px solid #dee2e6;
                padding: 12px;
            }
            QTableWidget::item:selected {
                background-color: rgba(33, 150, 243, 0.1);
            }
            QPushButton#exportBtn {
                background-color: #2196F3;
                min-width: 30px;
            }
            QPushButton#makeupBtn {
                background-color: #FFA500;
                min-width: 30px;
            }
            QPushButton#exportBtn:hover { background-color: #1976D2; }
            QPushButton#makeupBtn:hover { background-color: #FF8C00; }
        """)

    def get_classinfo(self):
        class_orm = classOrm().get_class()
        return [i['class_name'] for i in class_orm]

    def create_form(self, container):
        layout = QVBoxLayout(container)
        
        # 标题
        title = QLabel("发布新考试")
        title.setFont(QFont("Arial", 16, QFont.Bold))
        layout.addWidget(title)

        # 表单内容
        form_layout = QFormLayout()
        form_layout.setVerticalSpacing(15)

        # 考试名称
        self.exam_name = QLineEdit()
        form_layout.addRow(QLabel("考试名称："), self.exam_name)

        # 考试班级
        self.exam_class = QComboBox()
        self.exam_class.addItems(self.get_classinfo())
        form_layout.addRow(QLabel("考试班级："), self.exam_class)

        # 考试时间
        time_layout = QHBoxLayout()
        self.start_time = QDateTimeEdit()
        self.end_time = QDateTimeEdit()
        self.start_time.setDateTime(QDateTime.currentDateTime())
        self.end_time.setDateTime(QDateTime.currentDateTime().addDays(1))
        time_layout.addWidget(self.start_time)
        time_layout.addWidget(QLabel("  至  "))
        time_layout.addWidget(self.end_time)
        form_layout.addRow(QLabel("考试时间："), time_layout)

        # 发布按钮
        publish_btn = QPushButton("立即发布")
        publish_btn.clicked.connect(self.publish_exam)
        form_layout.addRow("", publish_btn)

        layout.addLayout(form_layout)

    def create_exam_list(self, container):
        layout = QVBoxLayout(container)
        
        # 标题
        title = QLabel("已发布考试列表")
        title.setFont(QFont("Arial", 16, QFont.Bold))
        layout.addWidget(title)

        # 表格
        self.exam_table = QTableWidget()
        self.exam_table.setColumnCount(4)
        self.exam_table.setHorizontalHeaderLabels(["考试名称", "考试时间", "考试班级", "操作"])
        self.exam_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.exam_table.horizontalHeader().setStretchLastSection(True)
        self.exam_table.verticalHeader().setVisible(False)
        self.exam_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.exam_table.setAlternatingRowColors(True)
        self.exam_table.setShowGrid(False)
        self.exam_table.verticalHeader().setDefaultSectionSize(50)
        layout.addWidget(self.exam_table)

    def init_example_data(self):
        examLis = Exam().get_exam(self.json.read()['user_id'])
        exams = [{
            "name": i['exam_name'],
            "start": i['start_time'],
            "end": i['end_time'],
            "class": i['class_name']
        } for i in examLis] if examLis else []
        for exam in exams:
            self.add_exam_to_table(exam)

    def publish_exam(self):
        exam_data = {
            "name": self.exam_name.text(),
            "class": self.exam_class.currentText(),
            "start": self.start_time.dateTime().toString("yyyy-MM-dd hh:mm"),
            "end": self.end_time.dateTime().toString("yyyy-MM-dd hh:mm")
        }

        if exam_data["name"]:
            self.insertTable(exam_data)
            self.add_exam_to_table(exam_data)
            self.clear_form()

    def insertTable(self, exam_data):
        exam = Exam()
        exam.write_exam({
            "exam_name": exam_data['name'],
            "class_name": exam_data['class'],
            "start_time": exam_data['start'],
            "end_time": exam_data['end'],
            "teacher_id": self.json.read()['user_id']
        })

    def add_exam_to_table(self, exam):
        row = self.exam_table.rowCount()
        self.exam_table.insertRow(row)
        
        self.exam_table.setItem(row, 0, QTableWidgetItem(exam["name"]))
        time_str = f"{exam['start']} ~ {exam['end']}"
        self.exam_table.setItem(row, 1, QTableWidgetItem(time_str))
        self.exam_table.setItem(row, 2, QTableWidgetItem(exam["class"]))
        
        # 按钮容器
        button_container = QWidget()
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(8)

        # 导出缺考按钮
        export_btn = QPushButton("导出")
        export_btn.setObjectName("exportBtn")
        export_btn.clicked.connect(lambda: self.export_absence(exam["name"], exam['class']))

        # 补签按钮（新增功能）
        makeup_btn = QPushButton("补签")
        makeup_btn.setObjectName("makeupBtn")
        makeup_btn.clicked.connect(lambda _, e=exam.copy(): self.handle_makeup(e))

        button_layout.addWidget(export_btn)
        button_layout.addWidget(makeup_btn)
        self.exam_table.setCellWidget(row, 3, button_container)

    def clear_form(self):
        self.exam_name.clear()
        self.exam_class.setCurrentIndex(0)
        self.start_time.setDateTime(QDateTime.currentDateTime())
        self.end_time.setDateTime(QDateTime.currentDateTime().addDays(1))

    def export_absence(self, exam_name, exam_class):
        # 点击按钮时才调用导出数据方法
        res = classRecord().export_absence(exam_name, exam_class)
        # 构建数据字典
        dic = {
            "序号": [i['id'] for i in res],
            "考试科目": [i['exam_name'] for i in res],
            "学号": [i['student_number'] for i in res],
            "姓名": [i['student_name'] for i in res],
            "班级": [i['exam_class'] for i in res],
            "教师": [i['teacher_name'] for i in res],
            "签到时间": [i['sign_in_time'] for i in res],
            "考试开始时间": [i['exam_start_time'] for i in res]
        }
        df = pd.DataFrame(dic)
        df.to_excel("D://Edge//absence.xlsx", index=False)
        CustomMessageBox().show_success("导出成功")

    def handle_makeup(self, exam_info):
        self.sign = ModernStudentForm(exam_info)
        self.sign.show()

    def paintEvent(self, event):
        # 背景渐变效果
        painter = QPainter(self)
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        gradient.setColorAt(0, QColor(240, 248, 255))  # 浅蓝色
        gradient.setColorAt(1, QColor(230, 240, 250))  # 更浅的蓝色
        painter.fillRect(self.rect(), gradient)
        super().paintEvent(event)


class ProfileView(QWidget):
    """现代化个人信息视图"""
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setupStyles()
        
    def initUI(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(30, 30, 30, 30)
        main_layout.setSpacing(20)
        
        # 表单项
        self.fields = {}
        
        # 用户名
        self.create_field(main_layout, "用户名：", "username")
        # 密码
        self.create_password_field(main_layout, "密码：", "password")
        # 性别
        self.create_combobox(main_layout, "性别：", "gender", ["男", "女", "其他"])
        # 电话
        self.create_field(main_layout, "电话：", "phone")
        # 邮箱
        self.create_field(main_layout, "邮箱：", "email")
        # 年龄
        self.create_spinbox(main_layout, "年龄：", "age", 0, 150)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(20)
        
        self.submit_btn = QPushButton("提交修改")
        self.submit_btn.setCursor(Qt.PointingHandCursor)
        self.submit_btn.clicked.connect(self.check_input)
        
        btn_layout.addStretch()
        btn_layout.addWidget(self.submit_btn)
        
        main_layout.addLayout(btn_layout)
        
    def create_field(self, layout, label_text, field_name):
        """创建文本输入字段"""
        h_layout = QHBoxLayout()
        label = QLabel(label_text)
        input_field = QLineEdit()
        input_field.setPlaceholderText(f"请输入{label_text.strip('：')}")
        h_layout.addWidget(label, stretch=1)
        h_layout.addWidget(input_field, stretch=3)
        layout.addLayout(h_layout)
        self.fields[field_name] = input_field
        
    def create_password_field(self, layout, label_text, field_name):
        """创建密码输入字段"""
        h_layout = QHBoxLayout()
        label = QLabel(label_text)
        input_field = QLineEdit()
        input_field.setEchoMode(QLineEdit.Password)
        input_field.setPlaceholderText("请输入新密码")
        h_layout.addWidget(label, stretch=1)
        h_layout.addWidget(input_field, stretch=3)
        layout.addLayout(h_layout)
        self.fields[field_name] = input_field
        
    def create_combobox(self, layout, label_text, field_name, items):
        """创建下拉选择框"""
        h_layout = QHBoxLayout()
        label = QLabel(label_text)
        combo = QComboBox()
        combo.addItems(items)
        h_layout.addWidget(label, stretch=1)
        h_layout.addWidget(combo, stretch=3)
        layout.addLayout(h_layout)
        self.fields[field_name] = combo
        
    def create_spinbox(self, layout, label_text, field_name, min_val, max_val):
        """创建数字输入框"""
        h_layout = QHBoxLayout()
        label = QLabel(label_text)
        spin = QSpinBox()
        spin.setRange(min_val, max_val)
        h_layout.addWidget(label, stretch=1)
        h_layout.addWidget(spin, stretch=3)
        layout.addLayout(h_layout)
        self.fields[field_name] = spin
        
    def setupStyles(self):
        """设置界面样式"""
        self.setStyleSheet("""
            QWidget {
                background-color: rgba(255, 255, 255, 0.3);
                border-radius: 8px;
            }
            QLabel {
                font-size: 14px;
                color: #666;
                min-width: 80px;
            }
            QLineEdit, QComboBox, QSpinBox {
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
                font-size: 14px;
            }
            QLineEdit:focus, QComboBox:hover, QSpinBox:hover {
                border-color: #007bff;
            }
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 10px 20px;
                font-size: 14px;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """)
        
    def check_input(self):
        """表单验证"""
        required_fields = {
            "username": "用户名",
            "password": "密码",
            "phone": "电话",
            "email": "邮箱"
        }
        
        missing = []
        for field, name in required_fields.items():
            widget = self.fields[field]
            if isinstance(widget, QLineEdit) and widget.text().strip() == "":
                missing.append(name)
                widget.setStyleSheet("border-color: #ff4444;")
            else:
                widget.setStyleSheet("")
        
        if missing:
            QMessageBox.warning(self, "输入错误", 
                              f"以下字段必须填写：\n{', '.join(missing)}")
            return False
            
        # 收集并打印表单数据
        form_data = {
            "name": self.fields["username"].text().strip(),
            "password": self.fields["password"].text(),
            "gender": self.fields["gender"].currentText(),
            "contact_number": self.fields["phone"].text().strip(),
            "email": self.fields["email"].text().strip(),
            "age": self.fields["age"].value()
        }
        LoginSchema().update_teacher(curJson.read()['user_id'], form_data)
        CustomMessageBox().show_success("修改成功")
        return True